package com.ruoyi.article.service.impl;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.article.domain.Article;
import com.ruoyi.article.domain.Material;
import com.ruoyi.article.domain.TranslationRequest;
import com.ruoyi.article.domain.VoiceTranslation;
import com.ruoyi.article.dtos.Result;
import com.ruoyi.article.dtos.voiceDto;
import com.ruoyi.article.mapper.ArticleMapper;
import com.ruoyi.article.service.IArticleService;
import com.ruoyi.config.SnowflakeIdGenerator;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;


/**
 * asdService业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-19
 */
@Service
public class ArticleServiceImpl implements IArticleService
{
    @Resource
    private ArticleMapper articleMapper;


    @Resource
    private SnowflakeIdGenerator idGenerator;


    @Value("${baidu.translate.token}") // 从配置文件中读取 token
    private String baiduToken;

    @Value("${baidu.translate.access_token}")
    private String access_token;
    private OkHttpClient HTTP_CLIENT;

    @Override
    public PageInfo<Article> listArticles(int pageNum, int pageSize,String title) {

        PageHelper.startPage(pageNum, pageSize);
        // 2. 执行 MyBatis 查询（会自动拼接分页 SQL）
        List<Article> list = articleMapper.listArticles(title);
        // 3. 封装分页信息（总条数、总页数等）
        return new PageInfo<>(list);
    }

    @Override
    public Article selectArticleById(String id) {

      return   articleMapper.selectArticleById(id);

    }

    @Override
    public Result insertArticle(Article article) {

        Long id = idGenerator.nextId();//雪花id

       int result= articleMapper.insertArticle(article,id);

       if(result>0){
           return Result.success();
       }
        return Result.error("文章插入失败");
    }

    @Override
    public Result deleteArticleByIds(String id) {

        Article article = selectArticleById(id);

        Integer isSublish = article.getIsSublish();

        if(isSublish==1){
            return Result.error("文章已经发布，不能下架");
        }

        int result= articleMapper.deleteArticleByIds(id);

        if(result>0){
            return Result.success();
        }
        return Result.error("文章删除失败");
    }


    @Override
    public Result updateArticleStatus(Long id, int isSublish) {
        isSublish=isSublish==1?0:1;

        int result= articleMapper.updateArticleStatus(id,isSublish);
        if(result>0){
            return Result.success();
        }
        return Result.error("文章状态修改失败");
    }

    @Override
    public Result updateArticle(Article article) {

      int result=  articleMapper.updateArticle(article);
        if(result>0){
            return Result.success();
        }

        return Result.error("文章编辑失败");
    }



    @Override
    public Result cnTranslationEn(TranslationRequest translationRequest) throws IOException{

        String text = translationRequest.getText();
        String fromLan = translationRequest.getFromLan();
        String toLan = translationRequest.getToLan();

        HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();
        MediaType mediaType = MediaType.parse("application/json");
      //  RequestBody body = RequestBody.create(mediaType, "{\"from\":\"zh\",\"to\":\"en\",\"q\":\"你好\"}");


        String jsonBody = String.format("{\"from\":\"%s\",\"to\":\"%s\",\"q\":\"%s\"}",
                fromLan,  // 使用前端传入的 fromLan
                toLan,    // 使用前端传入的 toLan
                text.replace("\"", "\\\"")  // 转义文本中的双引号
        );
        RequestBody body = RequestBody.create(mediaType, jsonBody);


        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer "+baiduToken)
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();

        String jsonData = response.body().string();



            JSONObject jsonObject = new JSONObject(jsonData);
            JSONObject resultObj = jsonObject.getJSONObject("result");
            JSONArray transArray = resultObj.getJSONArray("trans_result");
            JSONObject transObj = transArray.getJSONObject(0);
            String dstContent = transObj.getString("dst");

            System.out.println("提取的dst内容：" + dstContent);




        return  Result.success(dstContent);


    }


    @Override
    public Result voiceTranslation(VoiceTranslation voiceTranslation) throws IOException {

        System.out.println(voiceTranslation.toString());

        HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();

        // Get the base64 encoded voice file content
        String voiceBase64 = getFileContentAsBase64(voiceTranslation.getVoice(), false);

        // Create the request body with the base64 encoded voice
        MediaType mediaType = MediaType.parse("application/json");
        String requestBody = String.format("{\"from\":\"%s\",\"to\":\"%s\",\"format\":\"wav\",\"voice\":\"%s\"}",
                voiceTranslation.getFromLan(),
                voiceTranslation.getToLan(),
                voiceBase64);
        RequestBody body = RequestBody.create(mediaType, requestBody);

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/mt/v2/speech-translation")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer " + baiduToken)
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        String jsonData = response.body().string();

        JSONObject jsonResponse = new JSONObject(jsonData);
        JSONObject result = jsonResponse.getJSONObject("result");
        String fromText = result.getString("source");

        String toText = result.getString("target");

        voiceDto voiceDto = new voiceDto();
        voiceDto.setFromLan(fromText);

        voiceDto.setToLan(toText);



        System.out.println("提取的 source 内容: " + voiceDto);
        return  Result.success(voiceDto); // 假设 Result 能接收 source


    }

    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    public  String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }

        //System.out.println("base64的路径为"+base64);

        return base64;
    }



    // 从配置文件读取上传目录
    @Value("${voice.upload.path}")
    private String uploadPath;

    @Override
    public Result uploadVoice(MultipartFile multipartFile) {
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new IllegalArgumentException("上传的语音文件不能为空");
        }

        // 创建上传目录（如果不存在）
        File directory = new File(uploadPath);
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                throw new RuntimeException("创建上传目录失败: " + uploadPath);
            }
        }

        // 生成唯一文件名（UUID+原文件扩展名）
        String originalFilename = multipartFile.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        // 构建完整文件路径
        File destFile = new File(uploadPath + uniqueFileName);

        try {
            // 保存文件到服务器
            multipartFile.transferTo(destFile);
            // 返回绝对路径
            return Result.success(destFile.getAbsolutePath());
        } catch (IOException e) {
            // 记录详细错误日志
            throw new RuntimeException("保存语音文件失败", e);
        }
    }

    // 获取文件扩展名（包含点号）
    private String getFileExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf("."));
    }

}
